package com.bit.net;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务
 * <p>
 * 开启服务
 * </p>
 *
 * @since 2018/10/10
 */
@Slf4j
public class BaseNettyServer {

    private int port = 1000;

    private ChannelInitializer channelInitializer;

    public BaseNettyServer(int port, ChannelInitializer channelInitializer) {
        this.port = port;
        this.channelInitializer = channelInitializer;
    }

    protected void start0() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.WARN))
                    .childHandler(channelInitializer);

            serverBootstrap.bind(port)
                    .sync()
                    .channel()
                    .closeFuture()
                    .sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }


    public void start() throws Exception {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    start0();
                } catch (Exception e) {
                    log.warn("Start socket server cause an error.", e);
                }
            }
        }, "server-starter-thread").start();
    }
}
